package com.zhongxi.guoyuan.view.seller.offline;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.OffLineBaseFragment;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.seller.SellerCoinExchangeActivity;
import com.zhongxi.guoyuan.view.seller.SellerOffLineLoginActivity;
import com.zhongxi.guoyuan.view.seller.offline.mode.OrderInfoOffline;
import com.zhongxi.guoyuan.view.seller.offline.mode.OrderListBean;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2018/1/23.
 */

public class FragmentOffline extends OffLineBaseFragment implements MyScrollView.OnScrollListener {

    @Bind(R.id.tvStore)
    TextView mTvStore;
    @Bind(R.id.tv_shopid)
    TextView mTvShopid;
    @Bind(R.id.tvCoin)
    TextView mTvCoin;
    @Bind(R.id.tv_total_orderNum)
    TextView mTvTotalOrderNum;
    @Bind(R.id.tv_total_cash)
    TextView mTvTotalCash;
    @Bind(R.id.tvStartTime)
    TextView mTvStartTime;
    @Bind(R.id.tvEndTime)
    TextView mTvEndTime;
    @Bind(R.id.tvAllOrderNum)
    TextView mTvAllOrderNum;
    @Bind(R.id.tvPostNum)
    TextView mTvPostNum;
    @Bind(R.id.et_text_cancel)
    TextView mEtTextCancel;
    @Bind(R.id.ivQuery)
    ImageView mIvQuery;
    @Bind(R.id.etPhone)
    EditText mEtPhone;
    @Bind(R.id.et_clear)
    TextView mEtClear;
    @Bind(R.id.linearQuery)
    RelativeLayout mLinearQuery;
    @Bind(R.id.relaLayout)
    LinearLayout mRelaLayout;
    @Bind(R.id.rb0)
    RadioButton mRb0;
    @Bind(R.id.rb1)
    RadioButton mRb1;
    @Bind(R.id.rb2)
    RadioButton mRb2;
    @Bind(R.id.rb3)
    RadioButton mRb3;
    @Bind(R.id.scrollBody)
    LinearLayout mScrollBody;
    @Bind(R.id.linearBegin)
    LinearLayout mLinearBegin;
    @Bind(R.id.recycleView)
    RecyclerView mRecycleView;
    @Bind(R.id.myScrollView)
    MyScrollView mMyScrollView;
    @Bind(R.id.linearStop)
    LinearLayout mLinearStop;
    @Bind(R.id.linear)
    LinearLayout mLinear;
    @Bind(R.id.emptyView)
    FrameLayout mEmptyView;

    private OrderInfoOffline mOffline;
    private int mMeasuredHeight;
    private String mStime;  //开始时间
    private String mEtime;  //结束时间

    private List<OrderListBean> mLineList = new ArrayList<>();
    private SellerOffLineAdapter adapter;
    private boolean mIsLoadMore;
    private String mUserPhone = "";
    private boolean mIsMeasure = false;

    @Override
    protected void initParams() {
        super.initParams();
        mOffline = (OrderInfoOffline) getArguments().getSerializable("offline");
    }

    @Override
    protected View init() {
        View mView = UiUtils.inflate(R.layout.fragment_offlie_seller);
        ButterKnife.bind(this, mView);
        return mView;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mRelaLayout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!mIsMeasure) {
                    mMeasuredHeight = mRelaLayout.getMeasuredHeight();
                    mIsMeasure = true;
                }
                return true;
            }
        });
        mTvStore.setText(mOffline.console.name);
        mTvShopid.setText("ID:" + mOffline.console.sid);
        if ("100".equals(mOffline.console.discount)){
            mTvCoin.setText("无折扣");
        }else {
            mTvCoin.setText(mOffline.console.discount+" 折结账");
        }
        mTvTotalOrderNum.setText(String.valueOf(mOffline.orderNum));
        mTvTotalCash.setText(mOffline.totalAmount);
        SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd");
        String mS = mFormat.format(new Date());
        mStime = mS;
        mEtime = mS;
        mTvStartTime.setText(mStime);
        mTvEndTime.setText(mEtime);
        mRecycleView.setLayoutManager(new LinearLayoutManager(UiUtils.getContext()));
        mRecycleView.setNestedScrollingEnabled(false);
        if (adapter == null) {
            adapter = new SellerOffLineAdapter(mLineList);
            mRecycleView.setAdapter(adapter);
        }
    }

    @Override
    protected void initNet() {
        super.initNet();
        unsubscribe();
        mDisposable = Observable.concat(AddParameter.getInstance().getMarketOrderByTime(), AddParameter.getInstance().getMarketOrderList())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showProgressDialog();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (o instanceof OrderInfoOffline) {
                            MyApplication.getInstance().setSpValue(((OrderInfoOffline) o).safeobj);
                            if (((OrderInfoOffline) o).code == 1) {
                                if (!TextUtils.isEmpty(String.valueOf(((OrderInfoOffline) o).orderNum))) {
                                    mTvAllOrderNum.setText(String.valueOf(((OrderInfoOffline) o).orderNum));
                                }
                                if (!TextUtils.isEmpty(String.valueOf(((OrderInfoOffline) o).totalAmount))) {
                                    mTvPostNum.setText(String.valueOf(((OrderInfoOffline) o).totalAmount));
                                }
                            } else if (((OrderInfoOffline) o).code == 9002) {
                                getActivity().finish();
                                MyApplication.getInstance().sharedPrefrences.edit().putString("OffLinecredentials", "").commit();
                                startActivity(new Intent(UiUtils.getContext(), SellerOffLineLoginActivity.class));
                            } else {
                                ToastUtil.show(getString(R.string.loseData, ((OrderInfoOffline) o).code));
                            }
                        } else {
                            getorderListData(o);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismessProgressDialog();
                        ToastUtil.show(getString(R.string.load_error));
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        dismessProgressDialog();
                    }
                });

    }

    private void getorderListData(Object o) throws JSONException, IOException {
        JSONObject jsonObject = new JSONObject(((ResponseBody) o).string());
        JSONObject safeobj = jsonObject.optJSONObject("safeobj");
        MyApplication.getInstance().sharedPrefrences.edit().putString("now", safeobj.optString("now")).commit();
        MyApplication.getInstance().sharedPrefrences.edit().putString("sk", safeobj.optString("safestring")).commit();
        int mCode = jsonObject.optInt("code");
        JSONArray mJSONArray = jsonObject.optJSONArray("orderInfo");
        JSONObject mJSONObject = jsonObject.optJSONObject("user");
        if (page == 1) {
            mLineList.clear();
        }
        if (mCode == 1) {
            if (mJSONArray != null && (mJSONArray.length() > 0)) {
                List<OrderListBean> mListBeanList = new Gson().fromJson(mJSONArray.toString(), new TypeToken<List<OrderListBean>>() {
                }.getType());
                mLineList.addAll(mListBeanList);
                adapter.addUserData(mJSONObject);
                adapter.notifyDataSetChanged();
                mIsLoadMore = true;
                adapter.setLoadingState(adapter.LOADCOMPLENT);
            } else {
                if (page > 1) {
                    adapter.setLoadingState(adapter.LOADEND);
                    page--;
                }
                mIsLoadMore = false;
            }
            if (mLineList.size() > 0) {
                mRecycleView.setVisibility(View.VISIBLE);
                mEmptyView.setVisibility(View.INVISIBLE);
            } else {
                mRecycleView.setVisibility(View.INVISIBLE);
                mEmptyView.setVisibility(View.VISIBLE);
            }
        } else if (mCode == 9002) {
            ToastUtil.show(getString(R.string.loseCredentials));
            getActivity().finish();
            MyApplication.getInstance().sharedPrefrences.edit().putString("OffLinecredentials", "").commit();
            startActivity(new Intent(UiUtils.getContext(), SellerOffLineLoginActivity.class));
        } else {
            ToastUtil.show(getString(R.string.loseData, ((OrderInfoOffline) o).code));
            getActivity().finish();
        }
    }

    @Override
    protected void initListener() {
        super.initListener();
        mMyScrollView.setOnScrollListener(this);
        mEtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    mEtClear.setVisibility(View.VISIBLE);
                    mEtTextCancel.setVisibility(View.VISIBLE);
                    mEtTextCancel.setText(getString(R.string.search));
                } else {
                    mEtClear.setVisibility(View.GONE);
                    mEtTextCancel.setText(getString(R.string.cancel));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @OnClick({/*R.id.tvCoin,*/ R.id.tvStartTime, R.id.tvEndTime, R.id.ivQuery, R.id.et_text_cancel, R.id.et_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
//            case R.id.tvCoin:
//                Intent intent = new Intent(UiUtils.getContext(), SellerCoinExchangeActivity.class);
//                intent.putExtra("offline", "offline");
//                startActivity(intent);
//                break;
            case R.id.tvStartTime:
                showDateDialog(0);
                break;
            case R.id.tvEndTime:
                showDateDialog(1);
                break;
            case R.id.ivQuery:
                CommonTool.hideSoft(mEtPhone, getActivity());
                mUserPhone = mEtPhone.getText().toString().trim();
                page = 1;
                if (TextUtils.isEmpty(mUserPhone)) {
                    ToastUtil.show(getString(R.string.empty_phone));
                } else {
                    netWorkOrderList();
                }
                break;
            case R.id.et_text_cancel:  //搜索  去掉
                CommonTool.hideSoft(mEtPhone, getActivity());
                mUserPhone = mEtPhone.getText().toString().trim();
                page = 1;
                if (TextUtils.isEmpty(mUserPhone)) {
                    mEtTextCancel.setVisibility(View.GONE);
                }
                netWorkOrderList();
                break;
            case R.id.et_clear:   //清除
                CommonTool.showSoft(mEtPhone, getActivity());
                mEtPhone.setText("");
                mUserPhone = "";
                break;
        }
    }

    private void showDateDialog(final int index) {
        Calendar c = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                String mon = month + 1 + "";
                String text = "";
                if (month + 1 < 10 && dayOfMonth < 10) {
                    text = year + "-0" + mon + "-0" + dayOfMonth;
                } else if (month + 1 < 10 && dayOfMonth >= 10) {
                    text = year + "-0" + mon + "-" + dayOfMonth;
                } else if (month + 1 >= 10 && dayOfMonth < 10) {
                    text = year + "-" + mon + "-0" + dayOfMonth;
                } else {
                    text = year + "-" + mon + "-" + dayOfMonth;
                }
                if (index == 0) {
                    mTvStartTime.setText(text);
                    mStime = text;
                } else if (index == 1) {
                    mTvEndTime.setText(text);
                    mEtime = text;
                }
                timeOrderInfo();
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.setTitle("请选择时间：");
        dialog.getDatePicker().setCalendarViewShown(false);
        dialog.show();
    }

    public void timeOrderInfo() {
        unsubscribe();
        mDisposable = NetWork.getOffLineApi().sellerOrderByTimeApi(RelativeUrl.OFFLINEMARKETORDERBYTIME + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(true), mStime, mEtime)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showProgressDialog();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<OrderInfoOffline>() {
                    @Override
                    public void accept(OrderInfoOffline offline) throws Exception {
                        MyApplication.getInstance().setSpValue(offline.safeobj);
                        if (offline.code == 1) {
                            if (!TextUtils.isEmpty(String.valueOf(offline.orderNum))) {
                                mTvAllOrderNum.setText(String.valueOf(offline.orderNum));
                            }
                            if (!TextUtils.isEmpty(String.valueOf(offline.totalAmount))) {
                                mTvPostNum.setText(String.valueOf(offline.totalAmount));
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.show(getString(R.string.load_error));
                        dismessProgressDialog();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        dismessProgressDialog();
                    }
                });
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= mMeasuredHeight) {
            if (mScrollBody.getParent() == mLinearBegin) {
                mLinearBegin.removeView(mScrollBody);
                mLinearStop.addView(mScrollBody, new LinearLayout.LayoutParams(-1, -1));
            }
        } else {
            if (mScrollBody.getParent() == mLinearStop) {
                mLinearStop.removeView(mScrollBody);
                mLinearBegin.addView(mScrollBody, new LinearLayout.LayoutParams(-1, -1));
            }
        }
    }

    Handler mHandler=new Handler();
    @Override
    public void scrollBottom() {
        if (mIsLoadMore && CommonTool.isFirstScroll()) {
            adapter.setLoadingState(adapter.LOADING);
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                   mHandler.post(new Runnable() {
                       @Override
                       public void run() {
                           page++;
                           netWorkOrderList();
                       }
                   });
                }
            },1000);
        }
    }

    private void netWorkOrderList() {
        NetWork.getOffLineApi().sellerOrderListApi(RelativeUrl.OFFLINEMARKETORDERLIST + MyApplication.getInstance().getUrl(),
                MyApplication.getInstance().getCheck(true), page, mUserPhone)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        getorderListData(o);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtil.show(getString(R.string.load_error));
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
